#include "gatewayconfig.h"
#include <QDebug>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
GateWayConfig::GateWayConfig(const QString &fileName) : file_name(fileName) {
  qDebug() << QString("Load gateway config from file '%1'").arg(file_name);
  QFile jsonFile(file_name);
  if (jsonFile.open(QIODevice::ReadWrite | QIODevice::ReadOnly)) {
    auto jsonByte = jsonFile.readAll();
    jsonFile.close();
    auto jsonObj = QJsonDocument::fromJson(jsonByte).object();
    // connected_history
    auto his_list_val = jsonObj.value("connected_history");
    if (!his_list_val.isNull()) {
      if (his_list_val.isArray()) {
        auto his_arr = his_list_val.toArray();
        for (auto his : his_arr) {
          this->connected_history.append(
              {his.toObject().value("host").toString(),
               his.toObject().value("port").toInt()});
        }
      }
    }
    // last_connected
    auto last_conn_val = jsonObj.value("last_connected");
    if (!last_conn_val.isNull()) {
      this->last_connected = {last_conn_val.toObject().value("host").toString(),
                              last_conn_val.toObject().value("port").toInt()};
    }
    // bord_list
    auto bord_list_val = jsonObj.value("bord_list");
    if (!bord_list_val.isNull()) {
      if (bord_list_val.isArray()) {
        auto bord_arr = bord_list_val.toArray();
        for (auto bord : bord_arr) {
          this->bord_list.append(bord.toInt());
        }
      }
    }
    // last_bord
    auto last_bord_val = jsonObj.value("last_bord");
    if (!last_bord_val.isNull()) {
      this->last_bord = last_bord_val.toInt();
    }
  } else {
    qErrnoWarning("'gateway_config.json' load failed.");
    jsonFile.close();
  }
}

void GateWayConfig::SaveToFile() {
  qDebug() << QString("Save gateway config to file '%1'").arg(file_name);
  // TODO
}
